<!--
 * Copyright © 2022 XXXXXXXXX
 * @Author: zhangxiang
 * @Date: 2022-08-10 11:22:05
 * @LastEditors: zhangxiang
 * @LastEditTime: 2022-10-31 17:46:20
 * @Description:
 *
-->

<template>
  <div class="yaml-editor" :style="{ height: height }">
    <textarea ref="textarea"></textarea>
  </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css' // 样式
import 'codemirror/lib/codemirror.css' // 样式
import 'codemirror/theme/darcula.css' // 样式
import 'codemirror/mode/yaml/yaml' // 样式
import 'codemirror/addon/lint/lint' // 样式
import 'codemirror/addon/lint/yaml-lint' // 样式

window.jsyaml = require('js-yaml') // 引入js-yaml为codemirror提高语法检查核心支持

export default {
  name: 'YamlEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    height: {
      // 高度
      type: String,
      default: '50vh'
    },
    readOnly: {
      // 是否只读
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      yamlEditor: false
    }
  },
  watch: {
    /**
     * @description: 监听
     * @param {*} value
     * @return {*}
     */
    value(value) {
      const editorValue = this.yamlEditor.getValue()
      if (value !== editorValue) {
        this.yamlEditor.setValue(this.value)
      }
    }
  },
  mounted() {
    // 获取实例
    this.yamlEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      readOnly: this.readOnly, // 只读
      mode: 'text/x-yaml', // 语法model
      lineNumbers: true, // 显示行号
      indentUnit: 1,
      gutters: ['CodeMirror-lint-markers'], // 语法检查器
      theme: 'darcula', // 编辑器主题
      lineWrapping: true, // 自动换行
      lint: true // 开启语法检查
    })

    this.yamlEditor.setValue(this.value)
    this.yamlEditor.on('change', (cm) => {
      this.$emit('changed', cm.getValue()) // 抛出事件
      this.$emit('input', cm.getValue()) // 抛出事件
    })
  },
  methods: {
    /**
     * @description: 获取value
     * @return {*}
     */
    getValue() {
      return this.yamlEditor.getValue()
    }
  }
}
</script>

<style lang="less" scoped>
.yaml-editor {
  /deep/ .CodeMirror {
    height: 100%;
    min-height: 300px;
    padding-bottom: 30px;
  }
  /deep/ .CodeMirror-scroll {
    min-height: 300px;
  }
  /deep/.cm-s-rubyblue span.cm-string {
    color: #f08047;
  }
}
</style>
